package copyengine.dataLayer.rpc.moudle.request
{
	import copyengine.dataLayer.rpc.ICERpcManger;

	public class CERpcRequestManger implements ICERpcRequestModule
	{
		private static const DEFAULT_RETRY_TIME:int = 3;
		private static const DEFAULT_TIMEOUT_TIME:Number = 10 * 1000; //10s

		private var requestWrapperVector:Vector.<ICERequestWrapper>;

		private var requestURL:String;

		private var rpcManger:ICERpcManger;

		private var wrapperClass:Class;

		public function CERpcRequestManger(_requestURL:String)
		{
			requestURL = _requestURL;
			requestWrapperVector = new Vector.<ICERequestWrapper>();
		}

		public function initialize(_rpcManger:ICERpcManger, _wrapperClass:Class):void
		{
			rpcManger = _rpcManger;
			wrapperClass = _wrapperClass;
		}

		public function sendRpcRequest(_transferLayerData:*):void
		{
			var request:ICERequestWrapper = new wrapperClass();
			request.sendRequest(this, _transferLayerData, requestURL, DEFAULT_RETRY_TIME, DEFAULT_TIMEOUT_TIME);
			requestWrapperVector.push(request);
		}

		/**
		 * @private call by requestWrapper
		 */
		public function receiveServerResponse(_transferLayerData:*, _wrapper:ICERequestWrapper):void
		{
			removeRequestWrapper(_wrapper);
			rpcManger.receiveServerRespondData(_transferLayerData);
		}

		/**
		 * @private call by requestWrapper
		 */
		public function failedToRequest(_wrapper:ICERequestWrapper):void
		{
			removeRequestWrapper(_wrapper);
			rpcManger.sendRequestFailed();
		}

		private function removeRequestWrapper(_wrapper:ICERequestWrapper):void
		{
			for (var i:int = 0; i < requestWrapperVector.length; i++)
			{
				if (requestWrapperVector[i] == _wrapper)
				{
					_wrapper.dispose();
					requestWrapperVector.splice(i, 1);
					return;
				}
			}
		}

	}
}
